<?php

namespace App\Admin\Forms;

use App\Enums\DomainType;
use App\Models\Application;
use App\Models\DomainPool;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class SetupOssForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        Application::where('id', $this->payload['application_id'])
            ->update(['domain_pool_id' => $input['domain_pool_id']]);

        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $list = DomainPool::where('application_id', $this->payload['application_id'])
            ->where('type', DomainType::STORAGE)
            ->get();

        $options = [];

        foreach ($list as $item) {
            $options[$item->id] = $item->domain.' ('.$item->objectStorageService->bucket.')';
        }

        $this->select('domain_pool_id', 'CDN(存储桶)')
            ->required()
            ->options($options);
    }

    public function default(): array
    {
        return [
            'domain_pool_id' => Application::where('id', $this->payload['application_id'])->first()->domain_pool_id,
        ];
    }
}
